import asyncio
import aiohttp
import aiofiles
import ssl
import os

# 在全局范围内禁用 SSL 证书验证
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE

# 根据文件提供数据下载ts
async def aio_download():
    tasks = []
    async with aiohttp.ClientSession() as session:  # 提前准备好session
        async with aiofiles.open(f"实验数据/video2/m3u8文件/m3u8.txt", mode="r", encoding="utf-8") as f:
            i = 0  # 计数器
            async for line in f:
                if line.startswith("#"):
                    continue
                # line就是xxxx.ts
                ts_url = "https://vip1.155bf.com" + line.strip()  # 去掉没用的空格和换行
                name = f"temp_{i}.ts"
                file_path = f"实验数据/video2/{name}"
                i += 1
                if not os.path.exists(file_path):
                    task = asyncio.create_task(download_ts(ts_url, name, session))  # 创建任务
                    tasks.append(task)

            if tasks:  # 检查是否有任务添加到列表中
                if asyncio.get_event_loop().is_closed():
                    print("事件循环已关闭！无法执行任务。")
                else:
                    await asyncio.wait(tasks)  # 等待任务结束
            else:
                print("没有需要下载的文件！")
    print(f"{i}文件下载完毕！")

async def download_ts(url, name, session):
    try:
        async with session.get(url, ssl=ssl_context) as resp:
            async with aiofiles.open(f"实验数据/video2/{name}", mode="wb") as f:
                await f.write(await resp.content.read())  # 把下载到的内容写入到文件中
    except Exception as e:
        print(f"下载 {name} 时发生异常：{e}")

async def main():
    await aio_download()

if __name__ == '__main__':
    try:
        asyncio.run(main())
    except RuntimeError as e:
        print(f"发生异常：{e}")
